package io.iec.edp.caf.rest.filter;
import lombok.extern.slf4j.Slf4j;
//import org.jetbrains.annotations.NotNull;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class ServiceNotFoundFilter extends OncePerRequestFilter {

    private final static String errorMsg = "" +
            "<html><body>" +
            "<p>The REST service might not have been fully published yet, or the service may not exist.</p>"+
            "<p>You can try again later or contact the administrator to check whether the service has been registered in the application.</p>" +
            "</body></html>";

    private static boolean isFinishRegistered = false;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse httpResponse, FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(request, httpResponse);

        if(isFinishRegistered) return;
        int httpStatus = httpResponse.getStatus();
        if (httpStatus == HttpServletResponse.SC_NOT_FOUND) {
            //修改编码方式
            //httpResponse.setContentType("text/html;charset=utf-8");
            //修改返回文本，只能以追加的方式
            httpResponse.getWriter().write(errorMsg);
            //修改状态码
            //httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    public static void finishRegistered(){
        isFinishRegistered = true;
    }
}
